//
//  LGRViewController.m
//  LigerMobile
//
//  Created by John Gustafsson on 2/20/13.
//  Copyright (c) 2013-2014 ReachLocal Inc. All rights reserved.  https://github.com/reachlocal/liger-ios/blob/master/LICENSE
//

#import "LGRViewController.h"
#import "LGRPageFactory.h"




@interface LGRViewController ()
@property (nonatomic, strong) NSString *page;
@property (nonatomic, strong) NSDictionary *args;
@property (nonatomic, strong) NSDictionary *options;

@property (nonatomic, strong) NSMutableDictionary *buttons;
@end

@implementation LGRViewController

+ (NSString*)nativePage
{
	return nil;
}

- (id)initWithPage:(NSString*)page title:(NSString*)title args:(NSDictionary*)args options:(NSDictionary*)options
{
	return [self initWithPage:page title:title args:args options:options nibName:nil bundle:nil];
}

- (id)initWithPage:(NSString*)page title:(NSString*)title args:(NSDictionary*)args options:(NSDictionary*)options nibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    //本地页面初始方法
	self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	if (self) {
		NSAssert([self.class nativePage] == nil || [[self.class nativePage] isEqualToString:page], @"Native page name isn't the same as page argument.");
		self.page = page;
		self.args = args;
		self.title = title;
		self.options = options;
		
		self.buttons = [NSMutableDictionary dictionaryWithCapacity:2];
		[self addButtons];
        //
        #warning 解决modal出来的控制器消失
        [self initTabBar];
	}
	return self;
}

- (void)addButtons
{
	if ([self.options objectForKey:@"left"]) {
		NSDictionary *left = [self.options objectForKey:@"left"];
		UIBarButtonItem *leftButton = [self buttonFromDictionary:left];
		self.navigationItem.leftBarButtonItem = leftButton;
		self.buttons[[NSValue valueWithNonretainedObject:leftButton]] = left;
	}
	
	if ([self.options objectForKey:@"right"]) {
		NSDictionary *right = [self.options objectForKey:@"right"];
		UIBarButtonItem *rightButton =  [self buttonFromDictionary:right];
		self.navigationItem.rightBarButtonItem = rightButton;
		self.buttons[[NSValue valueWithNonretainedObject:rightButton]] = right;
	}
}

- (void)initTabBar
{
    self.navigationController.navigationBar.hidden = NO;
    //double ratio = 38.0 / 23.0;
    CGRect btnRect = CGRectMake(0., 0., 24, 24);//CGRectMake(0, 0, 38, 23)
    UIColor *color = [UIColor colorWithRed:55/255. green:175./255. blue:235./255. alpha:1.0];
    
//    color = [MxGlobal hexStringToColor:@"3aacde"];
//    UIImage *backImg = [MxGlobal createImageWithColor:color];
//    UIImage *image = [UIImage imageNamed:@""];
#warning 判断是否是第一个，如果是则不用加。
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    
    UIButton *leftButton = [[UIButton alloc] initWithFrame:btnRect];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"back_btn"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(leftDrawerButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
}

-(void)leftDrawerButtonPress:(id)sender
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}


- (UIBarButtonItem*)buttonFromDictionary:(NSDictionary*)buttonInfo
{
	NSAssert([buttonInfo isKindOfClass:[NSDictionary class]], @"options should look as follows {'right':{'button':'done'}}");
	
	NSDictionary *lookup = @{@"done": @(UIBarButtonSystemItemDone),
				 @"cancel": @(UIBarButtonSystemItemCancel),
				 @"edit": @(UIBarButtonSystemItemEdit),
				 @"save": @(UIBarButtonSystemItemSave),
				 @"add": @(UIBarButtonSystemItemAdd),
				 @"compose": @(UIBarButtonSystemItemCompose),
				 @"reply": @(UIBarButtonSystemItemReply),
				 @"action": @(UIBarButtonSystemItemAction),
				 @"organize": @(UIBarButtonSystemItemOrganize),
				 @"bookmarks": @(UIBarButtonSystemItemBookmarks),
				 @"search": @(UIBarButtonSystemItemSearch),
				 @"refresh": @(UIBarButtonSystemItemRefresh),
				 @"stop": @(UIBarButtonSystemItemStop),
				 @"camera": @(UIBarButtonSystemItemCamera),
				 @"trash": @(UIBarButtonSystemItemTrash),
				 @"play": @(UIBarButtonSystemItemPlay),
				 @"pause": @(UIBarButtonSystemItemPause),
				 @"rewind": @(UIBarButtonSystemItemRewind),
				 @"forward": @(UIBarButtonSystemItemFastForward),
				 @"undo": @(UIBarButtonSystemItemUndo),
				 @"redo": @(UIBarButtonSystemItemRedo)
				 };
	
	NSNumber *buttonValue = lookup[[buttonInfo[@"button"] lowercaseString]];
	if (buttonValue) {
		UIBarButtonSystemItem buttonSystemItem = buttonValue.integerValue;
		
		return [[UIBarButtonItem alloc] initWithBarButtonSystemItem:buttonSystemItem
								     target:self
								     action:@selector(buttonAction:)];
	} else {
		return [[UIBarButtonItem alloc] initWithTitle:buttonInfo[@"button"]
							style:UIBarButtonItemStylePlain
						       target:self
						       action:@selector(buttonAction:)];
	}
}

- (void)buttonAction:(id)sender
{
	NSDictionary *button = self.buttons[[NSValue valueWithNonretainedObject:sender]];
	[self buttonTapped:button];
}

- (void)buttonTapped:(NSDictionary*)button
{

}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	[self pageWillAppear];
	
	
	
}


#pragma mark - API

//直接打开本地页面/本地网页/超链接网页
- (void)openPage:(NSString*)page title:(NSString*)title args:(NSDictionary*)args options:(NSDictionary*)options parent:(LGRViewController*)parent success:(void (^)())success fail:(void (^)())fail
{
#warning 注意防止parent.navigationController为空
//	[self.collectionPage openPage:page title:title args:args options:options parent:parent success:success fail :fail];
    //delegate设计根控制器为导航控制器，导航控制器的根控制器又是firstPage.
    
    LGRViewController *lgrViewController = [LGRPageFactory controllerForPage:page title:title args:args options:options parent:parent];
    if(lgrViewController){
        if ([options[@"type"] isEqualToString:@"modal"]) {
            UINavigationController *navController = [[UINavigationController alloc]initWithRootViewController:lgrViewController];

            [parent.navigationController presentViewController:navController animated:YES completion:nil];
        }else
        {
            
        [parent.navigationController pushViewController:lgrViewController animated:YES];
        }
        
        
        //如果parent.navigationcontroller不存在，则设置appdelegate的rootviewcontroller为lgrviewcontroller.
    }
    
}



- (void)updateParent:(NSString*)destination args:(NSDictionary*)args success:(void (^)())success fail:(void (^)())fail
{
	if ([destination isKindOfClass:NSString.class]) {
		LGRViewController *page = self.parentPage;
		
		while (page) {
			if ([page.page isEqualToString:destination]) {
				[page childUpdates:args];
				success();
				return;
			}
			page = page.parentPage;
		}
	} else {
		[self.parentPage childUpdates:args];
		success();
		return;
	}
	
	fail();
}

- (void)closePage:(NSString*)rewindTo success:(void (^)())success fail:(void (^)())fail
{
	[self.collectionPage closePage:rewindTo sourcePage:self success:success fail:fail];
}

- (void)closePage:(NSString*)rewindTo sourcePage:(LGRViewController*)sourcePage success:(void (^)())success fail:(void (^)())fail
{

}

//打开系统页面，如相册控制器
- (void)openDialog:(NSString *)page title:(NSString*)title args:(NSDictionary*)args options:(NSDictionary*)options parent:(LGRViewController*)parent success:(void (^)())success fail:(void (^)())fail
{
	if (self.collectionPage) {
		[self.collectionPage openDialog:page
								  title:title
								   args:args
								options:options
								 parent:parent
								success:success
								   fail:fail];
	} else {
		UIViewController *new = [LGRPageFactory controllerForDialogPage:page title:title args:args options:options parent:parent];

		// Couldn't create a new view controller, possibly a broken plugin
		if (!new) {
			fail();
			return;
		}

		[self presentViewController:new animated:YES completion:^{
			success();
		}];
	}
}

- (void)closeDialog:(NSDictionary*)args success:(void (^)())success fail:(void (^)())fail
{
	// Internal error, we couldn't find the navigation controller
	
	
}

#pragma mark - Callbacks

- (void)dialogClosed:(NSDictionary*)args
{
}

- (void)childUpdates:(NSDictionary*)args
{
	self.args = args;
}

- (void)pageWillAppear
{
	
}

- (void)pushNotificationTokenUpdated:(NSString*)token error:(NSError*)error
{
	
}

- (void)notificationArrived:(NSDictionary*)userInfo state:(UIApplicationState)state
{
	
}

- (void)handleAppOpenURL:(NSURL*)url
{
	
}


@end
